package br.com.remedioCerto.service;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import br.com.remedioCerto.preference.EstoquePreference;

public class ValidadeAlarmeService extends IntentService {
	 
	 public static final String TAG = "ValidadeAlarmeService";
	 public static final String CREATE = "CREATE";
	 public static final String CANCEL = "CANCEL";
	     
	 private IntentFilter filter;
	
	public ValidadeAlarmeService() {
		super(TAG);
		filter = new IntentFilter();
		filter.addAction(CREATE);
		filter.addAction(CANCEL);
	}

	 @Override
	    protected void onHandleIntent(Intent intent) {
	        String action = intent.getAction();
	        if (filter.matchAction(action)) {          
	            execute(action);
	        }
	    }

	
	private void execute(String action) {
	    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	    
    	Intent alarme = new Intent("ESTOQUE_ALARME_RECEIVE");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, alarme, PendingIntent.FLAG_UPDATE_CURRENT);
 
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        String horarioDespertador = sp.getString("horario_alarme_validade", "12:00");
	    int hora = EstoquePreference.getHora(horarioDespertador);
	    int min = EstoquePreference.getMinuto(horarioDespertador);
	    
	    Calendar cal = Calendar.getInstance();
	    cal.set(Calendar.HOUR_OF_DAY, hora);
	    cal.set(Calendar.MINUTE, min);
	    cal.set(Calendar.SECOND, 0);

	    //86400000 = 24h
        if (CREATE.equals(action)) {
            am.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),86400000, pi);
            Log.i("DBG", CREATE);
        } else if (CANCEL.equals(action)) {
        	am.cancel(pi);
        	 Log.i("DBG", CANCEL);
        }
	}
	
}
